package guoanmaker.personal.business.controller;
/**
 * 
 * 
 * @author zhangjie
 * 
 */
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSSClient;
import com.qq.connect.oauth.Oauth;

import guoanmaker.personal.business.dao.PersonalUserDao;
import guoanmaker.personal.business.model.ApprReturn;
import guoanmaker.personal.business.model.PersonalUser;
import guoanmaker.personal.business.model.PersonalUserLandLog;
import guoanmaker.personal.business.model.ReturnResult;
import guoanmaker.personal.business.model.Uservo;
import guoanmaker.personal.business.repository.PersonalUserLandLogRepository;
import guoanmaker.personal.business.service.PersonalUserCouponService;
import guoanmaker.personal.business.service.PersonalUserService;
import guoanmaker.personal.business.service.PersonalUserServiceInterface;
import guoanmaker.personal.business.service.ThirdpartLoginService;
import guoanmaker.personal.helper.common.AjaxJson;
import guoanmaker.personal.helper.common.abstractobj.ApiController;
import guoanmaker.personal.helper.common.util.HttpGetUtil;
import guoanmaker.personal.helper.common.util.OSSUnitHelper;
import guoanmaker.personal.helper.common.util.PropertiesUtils;
import io.swagger.annotations.ApiOperation;
import redis.clients.jedis.Jedis;

@RestController
@RequestMapping(ApiController.USER_URL)
public class ThirdpartLoginController {
	  @Resource
	  private  PersonalUserServiceInterface personalUserServiceInterface;
	  @Resource
	  private  PersonalUserService personalUserService;
	  @Resource 
	  private  ThirdpartLoginService  thirdpartLoginService;
	  
	  @Autowired
	  private PersonalUserDao personalUserDao;
	  
	  @Autowired
	  private PersonalUserLandLogRepository personalUserLandLogRepository;
	  
	  @Resource
	  private PersonalUserCouponService personalUserCouponService;
	  @Resource
	  private AjaxJson ajaxJson;
	  
	  @Autowired  
	  private  HttpServletRequest request;
	  
	  /**
	   * 
	   * @param openid           String 类型    ：  微信   微博  qq 的openid
	   * @param type             String 类型     :  1:微信  3：微博  2：qq
	   * @param nickname         String 类型     :  昵称
	   * @param portriname       String 类型     :  头像存储地址
	   * @return
	   */
	  @ApiOperation(value="第三方登录客户端判断是否绑定过手机号", notes="第三方微信，qq,微博登录")
	  @RequestMapping(value = "thirdLoginforuser",method = RequestMethod.POST)
	  public AjaxJson thirdLoginforuser(String  openid,String type,String nickname,String portriname){
		  
		  ApprReturn  returnResult=new ApprReturn();
			try {
				returnResult = personalUserService.thirdLoginforuser(openid,type,nickname,portriname);
				ajaxJson.setSuccess(true).setStatus(200).setMsg("操作成功").setData(returnResult);
			} catch (Exception e) {
				ajaxJson.setSuccess(false).setStatus(500).setMsg("操作失败").setData(returnResult);
			}
		 
		  return  ajaxJson;
	  }    
	  /**
	  * @param openid           String 类型    ：        微信   微博  qq 的openid
	   * @param type             String 类型     :  1:微信  3：微博  2：qq
	   * @param nickname         String 类型     :  昵称
	   * @param portriname       String 类型     :  头像存储地址
	   * @param phone           String 类型     :   手机号
	   * @return
	   */
	  @ApiOperation(value="第三方登录绑定手机号")
	  @RequestMapping(value = "thirdLoginforphone",method = RequestMethod.POST)
	  public  AjaxJson   thirdLoginforphone(String  openid,String type,String phone,String nickname,String portriname){
		  ApprReturn  returnResult=new ApprReturn();
			try {
				    String sessionid=request.getSession().getId();
					Jedis jedis=new Jedis("123.56.48.63",6379); 
					jedis.auth("218007");
					jedis.set(sessionid, "1");
					String ss=jedis.get(phone);
					if(ss==null){
						jedis.set(phone, sessionid+",");
					}else{
						jedis.set(phone, ss+sessionid+",");
					}
					jedis.disconnect();
				returnResult = personalUserService.thirdLoginforphone(openid,type,phone,nickname,portriname);
				returnResult.setSessionid(sessionid);
				ajaxJson.setSuccess(true).setStatus(200).setMsg("操作成功").setData(returnResult);
			} catch (Exception e) {
				ajaxJson.setSuccess(false).setStatus(500).setMsg("操作失败").setData(returnResult);
			}
		  return  ajaxJson;
	  }
	  /**
	   * 
	   * @param type
	   * @param phone
	   * @return
	   */
	  @ApiOperation(value="第三方登录判断其他平台是否绑定")
	  @RequestMapping(value = "thirdLoginisExist",method = RequestMethod.POST)
	  public  AjaxJson   thirdLoginisExist(String type,String phone){
		  ApprReturn  returnResult=new ApprReturn();
			try {
				    String sessionid=request.getSession().getId();
					Jedis jedis=new Jedis("123.56.48.63",6379); 
					jedis.auth("218007");
					jedis.set(sessionid, "1");
					String ss=jedis.get(phone);
					if(ss==null){
						jedis.set(phone, sessionid+",");
					}else{
						jedis.set(phone, ss+sessionid+",");
					}
					jedis.disconnect();
				returnResult = personalUserService.thirdLoginisExist(type,phone);
				returnResult.setSessionid(sessionid);
				ajaxJson.setSuccess(true).setStatus(200).setMsg("操作成功").setData(returnResult);
			} catch (Exception e) {
				ajaxJson.setSuccess(false).setStatus(500).setMsg("操作失败").setData(returnResult);
			}
		  return  ajaxJson;
	  }
	  
	// 发送验证码
		@ApiOperation(value = "发送短信接口", notes = "发送短信")
		@RequestMapping(value ="/sendAPPVeryMessage",method = RequestMethod.POST)
		public AjaxJson sendAPPVeryMessage(String phone) {
			ReturnResult returnResult = new ReturnResult();
			try {
				returnResult = personalUserService.sendAPPVeryMessage(phone);
				ajaxJson.setSuccess(true).setStatus(200).setMsg("操作成功").setData(returnResult);
			} catch (Exception e) {
				ajaxJson.setSuccess(false).setStatus(500).setMsg("操作失败").setData(returnResult);
			}

			return ajaxJson;

		}
	  
	  
	  @ApiOperation(value="第三方微信登录", notes="第三方微信登录")
	  @RequestMapping("loginwx")
	  public void loginwx(HttpServletRequest request,
				HttpServletResponse response,String username) {
		    
	        response.setContentType("text/html;charset=utf-8");
	        try {
	        	String url = "https://open.weixin.qq.com/connect/qrconnect?" 
	        				+ "appid=" + PropertiesUtils.getPara("wxappkey")
	        				+ "&redirect_uri=" + PropertiesUtils.getPara("wxredirect_uri")
	        				+ "&response_type=code&scope=snsapi_login&state=wxlogin";
	        	System.out.println(url);
	            response.sendRedirect(url);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
		}
	  /**登录页面第三方登录请求，QQ登录
		 * @param request
		 * @param response
		 * @return
		 */
	    @ApiOperation(value="第三方qq登录", notes="第三方qq登录")
		@RequestMapping("loginqq")
		public void loginqq(HttpServletRequest request,
				HttpServletResponse response) {

	        response.setContentType("text/html;charset=utf-8");
	        try {
	            response.sendRedirect(new Oauth().getAuthorizeURL(request));
	        } catch (Exception e) {
	            e.printStackTrace();
	        }

		}
		
		/**登录页面第三方登录请求，微博登录
		 * @param request
		 * @param response
		 */
	    @ApiOperation(value="第三方微博登录", notes="第三方微博登录")
		@RequestMapping("loginwb")
		public void loginwb(HttpServletRequest request,
				HttpServletResponse response) {
			
	       response.setContentType("text/html;charset=utf-8");
	       try {
	        	String url = "https://api.weibo.com/oauth2/authorize?" 
	    				+ "client_id=" + PropertiesUtils.getPara("wbappkey")
	    				+ "&redirect_uri=" + PropertiesUtils.getPara("wbredirect_uri")
	    				+ "&response_type=code&state=wblogin"
	    				;
	        	System.out.println(url);
	            response.sendRedirect(url);
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	       
		}	
		
		
		
		/**微信第三方登录的回调地址
		 * @param request
		 * @param response
		 * @return
		 * @throws UnsupportedEncodingException
		 */
		@ApiOperation(value="第三方微信回调地址", notes="第三方微信回调地址")
		@RequestMapping("wxlogin")
		public Map<String, Object> wxloginback(HttpServletRequest request,
				HttpServletResponse response) throws UnsupportedEncodingException {  
			Map<String, Object>   map =new HashMap<>();
			String wxcode= request.getParameter("code");
			String wxstate=request.getParameter("state");
			//System.out.println("微信登录的参数 code + state:" + wxcode + " + " + wxstate);
			//System.out.println(request.getPathInfo());
			if(null!=wxcode&&!"".equals(wxcode)&&null!=wxstate&&!"".equals(wxstate)){
				//验证手机号
			   String openid=getOpenid(request,wxcode,wxstate);
			   List<PersonalUser>	users= personalUserServiceInterface.loginUserThird(openid);
			   if(users.size()>0){
				   //有openid 说明注册过 跳过验证手机号页面
				   wxLoginProcess(wxcode, wxstate, request);
				   map.put("home", 0);
			   }else{
				   //没有openid要调到验证手机号页面
				 map.put("wxvlidatePhone", 1);
				 map.put("wxcode", wxcode);
				 map.put("wxstate", wxstate);
			   }
			}
			 return map;
		}
		@ApiOperation(value="第三方qq回调地址", notes="第三方qq回调地址")
		@RequestMapping("qqlogin")
		public void toHomePage1(HttpServletRequest request,
				HttpServletResponse response) throws UnsupportedEncodingException {
            Map<String, Object> map =new HashMap<>();
			//System.out.println(request.getParameter("logintype"));
			String qqcode= request.getParameter("code");
			String qqstate=request.getParameter("state");
			//System.out.println(request.getPathInfo());
			if(null!=qqcode&&!"".equals(qqcode)&&null!=qqstate&&!"".equals(qqstate)){
				//QQ登录
				
				String  openid=getqqOpenid(request, qqcode, qqstate);
				  List<PersonalUser>	users= personalUserServiceInterface.loginqqUserThird(openid);
				   if(users.size()>0){
					   //有openid 说明注册过 跳过验证手机号页面
					   qqLoginProcess(qqcode,qqstate,request);
					   map.put("home", 0);
				   }else{
					   //没有openid要调到验证手机号页面
					 map.put("qqvlidatePhone", 1);
					 map.put("qqcode", qqcode);
					 map.put("qqstate", qqstate);
				   }

			}
		}
		/**微博第三方登录的回调地址
		 * @param request
		 * @param response
		 * @return
		 * @throws UnsupportedEncodingException
		 */
		@RequestMapping("wblogin")
		public  Map<String, Object> wbloginback(HttpServletRequest request,
				HttpServletResponse response) throws UnsupportedEncodingException {
			Map<String, Object>   map =new HashMap<>();
			String wbcode= request.getParameter("code");
			if(null!=wbcode&&!"".equals(wbcode)){
				//验证手机号
				   String openid=getUuid(request,wbcode);
				   List<PersonalUser>	users= personalUserServiceInterface.loginweiboUserThird(openid);
				   if(users.size()>0){
					   //有openid 说明注册过 跳过验证手机号页面
					   wbLoginProcess(wbcode,null,request);
					   map.put("home", 0);
				   }else{
					   //没有openid要调到验证手机号页面
					 map.put("wbvlidatePhone", 1);
					 map.put("wbcode", wbcode);
				   }
			}
			
         return   map;
		}
		
		
		
		//获取当前微信用户的openid
		public String getOpenid(HttpServletRequest request,String wxcode, String wxstate){
			
			String code = request.getParameter("code");// 客户端传回来的授权码
			String  atokenUrl="https://api.weixin.qq.com/sns/oauth2/access_token?"
					+ "appid=" + PropertiesUtils.getPara("wxappkey")
					+ "&secret=" + PropertiesUtils.getPara("wxappsecret")
					+ "&code=" + code
					+"&grant_type=authorization_code";
			String ret = HttpGetUtil.httpGet(atokenUrl);// 返回带token的json字符串
			if(null==ret||"".equals(ret)){
				return "0";
			}
			System.out.println(ret);
			com.alibaba.fastjson.JSONObject obj = JSON.parseObject(ret);
			String openId=(String) obj.get("openid");//取出openId
			return openId;
		}
		//获取当前qq用户的openid
		public String getqqOpenid(HttpServletRequest request,String qqcode, String qqstate){
			String code = request.getParameter("code");// 客户端传回来的授权码
			String atokenUrl = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code"
							+ "&code=" + code 
							+ "&client_id=" + PropertiesUtils.getPara("qqappkey")
							+ "&client_secret=" + PropertiesUtils.getPara("qqappsecret")
							+ "&redirect_uri=" + PropertiesUtils.getPara("qqredirect_uri");
			String ret = HttpGetUtil.httpGet(atokenUrl);// 返回带token的json字符串
			if(null==ret||"".equals(ret)){
				return "0";
			}
			String access_token =  getAccessToken(ret,"access_token");// (String) obj.get("access_token");// 取出token
			String openIdUrl = "https://graph.qq.com/oauth2.0/me?"
								+ "access_token=" + access_token;
			String oinfoma = HttpGetUtil.httpGet(openIdUrl);// 返回的openId信息json字符串
			com.alibaba.fastjson.JSONObject openidobj = JSON.parseObject(getOpenId(oinfoma));
			String openId =(String) openidobj.get("openid");// 取出openid
			return openId;
		}
		//获得微博用户的UUid
		public  String   getUuid(HttpServletRequest request,String wbcode){
			String code = request.getParameter("code");// 客户端传回来的授权码
			String  atokenUrl="https://api.weibo.com/oauth2/access_token";
					String grant_type= "authorization_code";
					String client_id=PropertiesUtils.getPara("wbappkey");
					String client_secret=PropertiesUtils.getPara("wbappsecret");
					String redirect_uri=PropertiesUtils.getPara("wbredirect_uri");
					System.out.println("grant_type:" + grant_type);
					System.out.println("client_id:" + client_id);
					System.out.println("client_secret:" + client_secret);
					System.out.println("redirect_uri:" + redirect_uri);
					System.out.println("code:" + code);
			String ret =HttpGetUtil.httpPost(atokenUrl,grant_type,code,client_id,client_secret,redirect_uri);//返回带token的json字符串
			if(null==ret||"".equals(ret)){
				System.out.println("exception in get token wb");
				return "0";
			}
			System.out.println(ret);
			com.alibaba.fastjson.JSONObject obj = JSON.parseObject(ret);
			String access_token=(String) obj.get("access_token");//取出token
			String uid=(String) obj.get("uid");//取出uid  第三方平台的id
			return uid;
			
		}
		
		
		
		
		//获取手机号发送验证码
		@ApiOperation(value="发送验证码", notes="发送验证码")
		@RequestMapping("sendMsg")
		public ReturnResult sendMsg(HttpServletRequest request,
				HttpServletResponse response, String telephone){
			return thirdpartLoginService.sendMsg(telephone);
			
		}
		
	
	 
		/**微信第三方登录过程
		 * @param wxcode
		 * @param wxstate
		 * @param request
		 * @throws UnsupportedEncodingException
		 * 
		 */
		private Map<String, Object> wxLoginProcess(String wxcode, String wxstate,
				HttpServletRequest request) throws UnsupportedEncodingException {
			Map<String, Object>  map =new HashMap<>();
			String code = request.getParameter("code");// 客户端传回来的授权码
			String  atokenUrl="https://api.weixin.qq.com/sns/oauth2/access_token?"
					+ "appid=" + PropertiesUtils.getPara("wxappkey")
					+ "&secret=" + PropertiesUtils.getPara("wxappsecret")
					+ "&code=" + code
					+"&grant_type=authorization_code";
			String ret = HttpGetUtil.httpGet(atokenUrl);// 返回带token的json字符串
			if(null==ret||"".equals(ret)){
				map.put("token", 0);
				return map;
			}
			System.out.println(ret);
			com.alibaba.fastjson.JSONObject obj = JSON.parseObject(ret);
			String access_token=(String) obj.get("access_token");//取出token
			String openId=(String) obj.get("openid");//取出openId
			String apiUrl="https://api.weixin.qq.com/sns/userinfo?"
					+ "access_token="+access_token
					+"&openid="+openId;
		
			String uinfoma = HttpGetUtil.httpGet(apiUrl);// 返回用户信息的字符串
			System.out.println(uinfoma);
			
		    if (uinfoma != null) {
		    	com.alibaba.fastjson.JSONObject oobj = JSON.parseObject(uinfoma);
				String sex = (1==(Integer)oobj.get("sex"))?"男":"女";
				String figureurl_qq_2 = (String) oobj.get("headimgurl");
				String  wchatName = (String) oobj.get("nickname");
				//String username=URLEncoder.encode(wchatName, "utf-8");   //在获得数据之后往数据库存之前先进行编码: 
				String username = filtername(wchatName);
				//String unionid = (String) oobj.get("unionid");  
				//(暂时不存)只要是同一个微信开放平台帐号下的公众号，用户的UnionID是唯一的。换句话说，同一用户，对同一个微信开放平台帐号下的不同应用，UnionID是相同的。
				System.out.println(
						" sex : " + sex
						+ " openId : " + openId
						+ " figureurl_qq_1 : " + figureurl_qq_2
						+ " username : " + username
						);
		    	//判断用户之前是否登陆过，如果登陆过，取出用户信息，设置登录，返回，否则获取用户信息
		    	List<PersonalUser>	users= personalUserServiceInterface.loginUserThird(openId);
		    	//如果用户曾经用微信登陆过
		    	 if(users.size()>0){
				    	//update  用户信息
		    		    if(users.get(0).getWechatopenid().equals(openId)){
		    		    	users.get(0).setWechatopenid(openId);     //获取openid
		    		    	users.get(0).setWechatnickname(username); //获取昵称
		    		    	users.get(0).setCreateTime(new Date());
		    		    	if(users.get(0).getWechatportrait()!=null&&users.get(0).getWechatportraitN()!=null){
		    		    		OSSClient client = OSSUnitHelper.getOSSClient(); 
		    		    		OSSUnitHelper.deleteFile(client, ApiController.PORTRAINT_URL, users.get(0).getWechatportraitN()); 
		    		    	}
		    		    	String str=saveUserAvatar(figureurl_qq_2);
		    		    	String sarr[]=str.split(",");
		    		    	users.get(0).setWechatportrait(sarr[0]);
		    		    	users.get(0).setWechatportraitN(sarr[1]);
		    		    	// users.get(0).setThirdtype(thirdtype);
		    		    	request.getSession().setAttribute("sysUser", users.get(0));
		    		    	personalUserService.insertUser(users.get(0));
		    		    	//返回首页
		    		    	map.put("home",1);
		    		    }else{
		    		    	 PersonalUser  personalUser=new PersonalUser();
						     personalUser.setWechatopenid(openId);
						     personalUser.setWechatnickname(username); //获取昵称
						     personalUser.setCreateTime(new Date());
							 String[] sarr;
							 String str=saveUserAvatar(figureurl_qq_2);
							 sarr=str.split(",");
							 personalUser.setWechatportrait(sarr[0]);
							 personalUser.setWechatportraitN(sarr[1]);
							// users.get(0).setThirdtype(thirdtype);
							 request.getSession().setAttribute("sysUser", personalUser);
						     personalUserService.insertUser(personalUser);  
						     map.put("home",1);
		    		    }
				    }
		    	
		    }
			return map;

			
		}
		
		//手机号验证跳首页之前  第三方wx登录参数的存储
		@RequestMapping("validatewxPhoneProcess")
		public @ResponseBody   Map<String, Object>  validatePhoneProcess(String wxcode, String wxstate,
				HttpServletRequest request,String telephone){
			Map<String, Object>  map =new HashMap<>();
			String code = request.getParameter("code");// 客户端传回来的授权码
			String  atokenUrl="https://api.weixin.qq.com/sns/oauth2/access_token?"
					+ "appid=" + PropertiesUtils.getPara("wxappkey")
					+ "&secret=" + PropertiesUtils.getPara("wxappsecret")
					+ "&code=" + code
					+"&grant_type=authorization_code";
			String ret = HttpGetUtil.httpGet(atokenUrl);// 返回带token的json字符串
			if(null==ret||"".equals(ret)){
				map.put("token", 0);
				return map;
			}
			System.out.println(ret);
			com.alibaba.fastjson.JSONObject obj = JSON.parseObject(ret);
			String access_token=(String) obj.get("access_token");//取出token
			String openId=(String) obj.get("openid");//取出openId
			
			String apiUrl="https://api.weixin.qq.com/sns/userinfo?"
					+ "access_token="+access_token
					+"&openid="+openId;
		
			String uinfoma = HttpGetUtil.httpGet(apiUrl);// 返回用户信息的字符串
			System.out.println(uinfoma);
			
			//判断用户之前是否登陆过，如果登陆过，取出用户信息，设置登录，返回，否则获取用户信息
			
			 if (uinfoma != null) {
					com.alibaba.fastjson.JSONObject oobj = JSON.parseObject(uinfoma);
					String sex = (1==(Integer)oobj.get("sex"))?"男":"女";
					String figureurl_qq_2 = (String) oobj.get("headimgurl");
					String  wchatName = (String) oobj.get("nickname");
					//String username=URLEncoder.encode(wchatName, "utf-8");   //在获得数据之后往数据库存之前先进行编码: 
					String username = filtername(wchatName);
					//String unionid = (String) oobj.get("unionid");  
					//(暂时不存)只要是同一个微信开放平台帐号下的公众号，用户的UnionID是唯一的。换句话说，同一用户，对同一个微信开放平台帐号下的不同应用，UnionID是相同的。
					System.out.println(
							" sex : " + sex
							+ " openId : " + openId
							+ " figureurl_qq_1 : " + figureurl_qq_2
							+ " username : " + username
							);
					
					List<PersonalUser>	users= personalUserService.findUsername(telephone);
					//如果有说明注册过
					 if(users.size()>0){
						 //注册过手机号但是没有第三方登录过微信
						 if(users.get(0).getWechatopenid()==null){
									//之前未登录过
							 users.get(0).setWechatopenid(openId);     //获取openid
							 users.get(0).setWechatnickname(username); //获取昵称
							 users.get(0).setCreateTime(new Date());
							 String str=saveUserAvatar(figureurl_qq_2);
							 String sarr[]=str.split(",");
							 users.get(0).setWechatportrait(sarr[0]);
							 users.get(0).setWechatportraitN(sarr[1]);
							// users.get(0).setThirdtype(thirdtype);
							 request.getSession().setAttribute("sysUser", users.get(0));
						     personalUserService.insertUser(users.get(0));
								    //返回首页
						     map.put("home",1);
							//注册过手机号，也同时用过微信登录过
						 }else{
							 //曾 经注册而且用同一个微信手机号绑定
							 if(users.get(0).getWechatopenid().equals(openId)){
								 
								 users.get(0).setWechatnickname(username); //获取昵称
								 users.get(0).setCreateTime(new Date());
								 if(users.get(0).getWechatportrait()!=null&&users.get(0).getWechatportraitN()!=null){
									 OSSClient client = OSSUnitHelper.getOSSClient(); 
									 OSSUnitHelper.deleteFile(client, ApiController.PORTRAINT_URL, users.get(0).getWechatportraitN()); 
								 }
								 String str=saveUserAvatar(figureurl_qq_2);
								 String sarr[]=str.split(",");
								 users.get(0).setWechatportrait(sarr[0]);
								 users.get(0).setWechatportraitN(sarr[1]);
								 request.getSession().setAttribute("sysUser", users.get(0));
								 personalUserService.insertUser(users.get(0));
								 map.put("home",1);
								// 如果同一个手机号登录不同的微信号
							 }else{
								 //绑定新的微信号登录
								 users.get(0).setWechatopenid(openId);
								 users.get(0).setWechatnickname(username); //获取昵称
								 users.get(0).setCreateTime(new Date());
								 if(users.get(0).getWechatportrait()!=null&&users.get(0).getWechatportraitN()!=null){
									 OSSClient client = OSSUnitHelper.getOSSClient(); 
									 OSSUnitHelper.deleteFile(client, ApiController.PORTRAINT_URL, users.get(0).getWechatportraitN()); 
								 }
								 String str=saveUserAvatar(figureurl_qq_2);
								 String sarr[]=str.split(",");
								 users.get(0).setWechatportrait(sarr[0]);
								 users.get(0).setWechatportraitN(sarr[1]);
								 request.getSession().setAttribute("sysUser", users.get(0));
								 personalUserService.insertUser(users.get(0));
								 map.put("home",1);
								 
							 }
						 }
					//如果没有注册过手机号	 
					  }else{
						  List<PersonalUser>	puser=  personalUserService.loginUserThird(openId);
						  if(puser.size()>0){
							  //有openid  更新手机号
							     puser.get(0).setUsername(telephone);
							     puser.get(0).setWechatnickname(username); //获取昵称
							     puser.get(0).setCreateTime(new Date());
							     if(puser.get(0).getWechatportrait()!=null&&puser.get(0).getWechatportraitN()!=null){
							    	 OSSClient client = OSSUnitHelper.getOSSClient(); 
							    	 OSSUnitHelper.deleteFile(client, ApiController.PORTRAINT_URL, puser.get(0).getWechatportraitN()); 
							     }
								 String str=saveUserAvatar(figureurl_qq_2);
								 String sarr[]=str.split(",");
								 puser.get(0).setWechatportrait(sarr[0]);
								 puser.get(0).setWechatportraitN(sarr[1]);
								// users.get(0).setThirdtype(thirdtype);
								 request.getSession().setAttribute("sysUser", puser.get(0));
							     personalUserService.insertUser(puser.get(0));  
							     map.put("home",1);
						  }else{
							  //没有openid和手机号    insert 手机号和三方登录等信息
							     PersonalUser  personalUser=new PersonalUser();
							     personalUser.setUsername(telephone);
							     personalUser.setWechatopenid(openId);
							     personalUser.setWechatnickname(username); //获取昵称
							     personalUser.setCreateTime(new Date());
								 String[] sarr;
								 String str=saveUserAvatar(figureurl_qq_2);
								 sarr=str.split(",");
								 personalUser.setWechatportrait(sarr[0]);
								 personalUser.setWechatportraitN(sarr[1]);
								// users.get(0).setThirdtype(thirdtype);
								 request.getSession().setAttribute("sysUser", personalUser);
							     personalUserService.insertUser(personalUser);  
							     map.put("home",1);
							  
						  }
					  }
			 
			 }else{
				 //返回用户信息出错
				 map.put("Nouinfoma", -1);
			 }
			 
		
			return map;
	
		}
		
		
		
		/**QQ第三方登录过程
		 * @param qqcode
		 * @param qqstate
		 * @param request
		 * @return
		 * @throws UnsupportedEncodingException
		 */
		private Map<String, Object>  qqLoginProcess(String qqcode, String qqstate,
				HttpServletRequest request) throws UnsupportedEncodingException {
			Map<String, Object>  map =new HashMap<>();
			String code = request.getParameter("code");// 客户端传回来的授权码
			String atokenUrl = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code"
							+ "&code=" + code 
							+ "&client_id=" + PropertiesUtils.getPara("qqappkey")
							+ "&client_secret=" + PropertiesUtils.getPara("qqappsecret")
							+ "&redirect_uri=" + PropertiesUtils.getPara("qqredirect_uri");
			String ret = HttpGetUtil.httpGet(atokenUrl);// 返回带token的json字符串
			if(null==ret||"".equals(ret)){
				map.put("token", 0);
				return map;
			}
			String access_token =  getAccessToken(ret,"access_token");// (String) obj.get("access_token");// 取出token
			String openIdUrl = "https://graph.qq.com/oauth2.0/me?"
								+ "access_token=" + access_token;
			String oinfoma = HttpGetUtil.httpGet(openIdUrl);// 返回的openId信息json字符串
			//System.out.println(oinfoma);
			com.alibaba.fastjson.JSONObject openidobj = JSON.parseObject(getOpenId(oinfoma));
			String openId =(String) openidobj.get("openid");// 取出openid
			
			String apiUrl = "https://graph.qq.com/user/get_user_info?"
							+ "access_token="	+ access_token 
							+ "&oauth_consumer_key=" + PropertiesUtils.getPara("qqappkey")
							+ "&openid=" + openId;
			String uinfoma = HttpGetUtil.httpGet(apiUrl);// 返回用户信息的字符串
			System.out.println(uinfoma);
			if (uinfoma != null) {
				com.alibaba.fastjson.JSONObject oobj = JSON.parseObject(uinfoma);
				String sex = (String) oobj.get("gender");
				String figureurl_qq_2 = (String) oobj.get("figureurl_qq_2");
				String  wchatName = (String) oobj.get("nickname");
				//String username=URLEncoder.encode(wchatName, "utf-8");   //在获得数据之后往数据库存之前先进行编码:
				String username = filtername(wchatName);
				System.out.println(
						" sex : " + sex
						+ " openId : " + openId
						+ " figureurl_qq_1 : " + figureurl_qq_2
						+ " username : " + username
						);
				//判断用户之前是否登陆过，如果登陆过，取出用户信息，设置登录，返回，否则获取用户信息
			    List<PersonalUser>   pus=personalUserServiceInterface.loginqqUserThird(openId);
			  //如果用户曾经用微信登陆过
		    	 if(pus.size()>0){
				    	//update  用户信息
		    		    if(pus.get(0).getQqopenid().equals(openId)){
		    		    	pus.get(0).setQqopenid(openId);     //获取openid
		    		    	pus.get(0).setQqnickname(username); //获取昵称
		    		    	if(pus.get(0).getQqportrait()!=null&&pus.get(0).getQqportraitN()!=null){
		    		    		OSSClient client = OSSUnitHelper.getOSSClient(); 
		    		    		OSSUnitHelper.deleteFile(client, ApiController.PORTRAINT_URL, pus.get(0).getQqportraitN()); 
		    		    	}
		    		    	String str=saveUserAvatar(figureurl_qq_2);
		    		    	String sarr[]=str.split(",");
		    		    	pus.get(0).setQqportrait(sarr[0]);
		    		    	pus.get(0).setQqportraitN(sarr[1]);
		    		    	personalUserService.insertUser(pus.get(0));
		    		    	request.getSession().setAttribute("sysUser", pus.get(0));
		    		    	//返回首页
		    		    	map.put("home",1);
		    		    }else{
		    		    	 PersonalUser  personalUser=new PersonalUser();
						     personalUser.setQqopenid(openId);
						     personalUser.setQqnickname(username); //获取昵称
							 String[] sarr;
							 String str=saveUserAvatar(figureurl_qq_2);
							 sarr=str.split(",");
							 personalUser.setQqportrait(sarr[0]);
							 personalUser.setQqportraitN(sarr[1]);
							 request.getSession().setAttribute("sysUser", personalUser);
						     personalUserService.insertUser(personalUser);  
						     map.put("home",1);
		    		    }
				    }
		    	
			    
		       
			}

			return map;
			
		}
		
		//手机号验证跳首页之前  第三方qq登录参数的存储
		
		@RequestMapping("validateqqPhoneProcess")
		public @ResponseBody   Map<String, Object>  validateqqPhoneProcess(String wxcode, String wxstate,
				HttpServletRequest request,String telephone){
			Map<String, Object>  map =new HashMap<>();
			String code = request.getParameter("code");// 客户端传回来的授权码
			String atokenUrl = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code"
							+ "&code=" + code 
							+ "&client_id=" + PropertiesUtils.getPara("qqappkey")
							+ "&client_secret=" + PropertiesUtils.getPara("qqappsecret")
							+ "&redirect_uri=" + PropertiesUtils.getPara("qqredirect_uri");
			String ret = HttpGetUtil.httpGet(atokenUrl);// 返回带token的json字符串
			if(null==ret||"".equals(ret)){
				map.put("token", 0);
				return map;
			}
			String access_token =  getAccessToken(ret,"access_token");// (String) obj.get("access_token");// 取出token
			String openIdUrl = "https://graph.qq.com/oauth2.0/me?"
								+ "access_token=" + access_token;
			String oinfoma = HttpGetUtil.httpGet(openIdUrl);// 返回的openId信息json字符串
			//System.out.println(oinfoma);
			com.alibaba.fastjson.JSONObject openidobj = JSON.parseObject(getOpenId(oinfoma));
			String openId =(String) openidobj.get("openid");// 取出openid
			
			String apiUrl = "https://graph.qq.com/user/get_user_info?"
							+ "access_token="	+ access_token 
							+ "&oauth_consumer_key=" + PropertiesUtils.getPara("qqappkey")
							+ "&openid=" + openId;
			String uinfoma = HttpGetUtil.httpGet(apiUrl);// 返回用户信息的字符串
			System.out.println(uinfoma);
			
			//判断用户之前是否登陆过，如果登陆过，取出用户信息，设置登录，返回，否则获取用户信息
			
			 if (uinfoma != null) {
				    com.alibaba.fastjson.JSONObject oobj = JSON.parseObject(uinfoma);
					String sex = (String) oobj.get("gender");
					String figureurl_qq_2 = (String) oobj.get("figureurl_qq_2");
					String  wchatName = (String) oobj.get("nickname");
					//String username=URLEncoder.encode(wchatName, "utf-8");   //在获得数据之后往数据库存之前先进行编码:
					String username = filtername(wchatName);
					System.out.println(
							" sex : " + sex
							+ " openId : " + openId
							+ " figureurl_qq_1 : " + figureurl_qq_2
							+ " username : " + username
							);
					List<PersonalUser>	users= personalUserService.findUsername(telephone);
					//如果有说明注册过
					 if(users.size()>0){
						 //注册过手机号但是没有第三方登录过微信
						 if(users.get(0).getQqopenid()==null){
									//之前未登录过
							 users.get(0).setQqopenid(openId);     //获取openid
							 users.get(0).setQqnickname(username); //获取昵称
							 users.get(0).setCreateTime(new Date());
							 String str=saveUserAvatar(figureurl_qq_2);
							 String sarr[]=str.split(",");
							 users.get(0).setQqportrait(sarr[0]);
							 users.get(0).setQqportraitN(sarr[1]);
							// users.get(0).setThirdtype(thirdtype);
							 request.getSession().setAttribute("sysUser", users.get(0));
						     personalUserService.insertUser(users.get(0));
								    //返回首页
						     map.put("home",1);
							//注册过手机号，也同时用过微信登录过
						 }else{
							 //曾 经注册而且用同一个微信手机号绑定
							 if(users.get(0).getQqopenid().equals(openId)){
								 
								 users.get(0).setQqnickname(username); //获取昵称
								 users.get(0).setCreateTime(new Date());
								 if(users.get(0).getQqportrait()!=null&&users.get(0).getQqportraitN()!=null){
									 OSSClient client = OSSUnitHelper.getOSSClient(); 
									 OSSUnitHelper.deleteFile(client, ApiController.PORTRAINT_URL, users.get(0).getQqportraitN()); 
								 }
								 String str=saveUserAvatar(figureurl_qq_2);
								 String sarr[]=str.split(",");
								 users.get(0).setQqportrait(sarr[0]);
								 users.get(0).setQqportraitN(sarr[1]);
								 request.getSession().setAttribute("sysUser", users.get(0));
								 personalUserService.insertUser(users.get(0));
								 map.put("home",1);
								// 如果同一个手机号登录不同的微信号
							 }else{
								 //绑定新的微信号登录
								 users.get(0).setQqopenid(openId);
								 users.get(0).setQqnickname(username); //获取昵称
								 users.get(0).setCreateTime(new Date());
								 if(users.get(0).getQqportrait()!=null&&users.get(0).getQqportraitN()!=null){
									 OSSClient client = OSSUnitHelper.getOSSClient(); 
									 OSSUnitHelper.deleteFile(client, ApiController.PORTRAINT_URL, users.get(0).getQqportraitN()); 
								 }
								 String str=saveUserAvatar(figureurl_qq_2);
								 String sarr[]=str.split(",");
								 users.get(0).setQqportrait(sarr[0]);
								 users.get(0).setQqportraitN(sarr[1]);
								 request.getSession().setAttribute("sysUser", users.get(0));
								 personalUserService.insertUser(users.get(0));
								 map.put("home",1);
								 
							 }
						 }
					//如果没有注册过手机号	 
					  }else{
						  List<PersonalUser>	puser=  personalUserService.loginqqUserThird(openId);
						  if(puser.size()>0){
							  //有openid  更新手机号
							     puser.get(0).setUsername(telephone);
							     puser.get(0).setQqnickname(username); //获取昵称
							     puser.get(0).setCreateTime(new Date());
							     if(puser.get(0).getQqportrait()!=null&&puser.get(0).getQqportraitN()!=null){
							    	 OSSClient client = OSSUnitHelper.getOSSClient(); 
							    	 OSSUnitHelper.deleteFile(client, ApiController.PORTRAINT_URL, puser.get(0).getQqportraitN()); 
							     }
								 String str=saveUserAvatar(figureurl_qq_2);
								 String sarr[]=str.split(",");
								 puser.get(0).setQqportrait(sarr[0]);
								 puser.get(0).setQqportraitN(sarr[1]);
								 request.getSession().setAttribute("sysUser", puser.get(0));
							     personalUserService.insertUser(puser.get(0));  
							     map.put("home",1);
						  }else{
							  //没有openid和手机号    insert 手机号和三方登录等信息
							     PersonalUser  personalUser=new PersonalUser();
							     personalUser.setUsername(telephone);
							     personalUser.setQqopenid(openId);
							     personalUser.setQqnickname(username); //获取昵称
							     personalUser.setCreateTime(new Date());
								 String[] sarr;
								 String str=saveUserAvatar(figureurl_qq_2);
								 sarr=str.split(",");
								 personalUser.setQqportrait(sarr[0]);
								 personalUser.setQqportraitN(sarr[1]);
								 request.getSession().setAttribute("sysUser",personalUser);
							     personalUserService.insertUser(personalUser);  
							     map.put("home",1);
							  
						  }
					  }
			 
			 }else{
				 //返回用户信息出错
				 map.put("Nouinfoma", -1);
			 }
			 
		
			return map;
	
		}
		
		
		/**微博第三方登录过程
		 * @param wbcode
		 * @param wbstate
		 * @param request
		 * @throws UnsupportedEncodingException
		 */
		private Map<String, Object> wbLoginProcess(String wbcode, String wbstate,
				HttpServletRequest request) throws UnsupportedEncodingException {
			Map<String, Object> map=new HashMap<>();
			String code = request.getParameter("code");// 客户端传回来的授权码
			String  atokenUrl="https://api.weibo.com/oauth2/access_token";
					String grant_type= "authorization_code";
					String client_id=PropertiesUtils.getPara("wbappkey");
					String client_secret=PropertiesUtils.getPara("wbappsecret");
					String redirect_uri=PropertiesUtils.getPara("wbredirect_uri");
					System.out.println("grant_type:" + grant_type);
					System.out.println("client_id:" + client_id);
					System.out.println("client_secret:" + client_secret);
					System.out.println("redirect_uri:" + redirect_uri);
					System.out.println("code:" + code);
			String ret =HttpGetUtil.httpPost(atokenUrl,grant_type,code,client_id,client_secret,redirect_uri);//返回带token的json字符串
			if(null==ret||"".equals(ret)){
				System.out.println("exception in get token wb");
				map.put("token", 0);
				return map;
			}
			System.out.println(ret);
			com.alibaba.fastjson.JSONObject obj = JSON.parseObject(ret);
			String access_token=(String) obj.get("access_token");//取出token
			String uid=(String) obj.get("uid");//取出uid  第三方平台的id
			
			String apiUrl="https://api.weibo.com/2/users/show.json?"
					+ "access_token="+access_token
					+ "&uid="+uid;
			
			String uinfoma = HttpGetUtil.httpGet(apiUrl);// 返回用户信息的字符串
			System.out.println(uinfoma);
			if (uinfoma != null) {
				com.alibaba.fastjson.JSONObject oobj = JSON.parseObject(uinfoma);
				
				String sex=("m".equals((String)oobj.get("gender")))?"男":"女";
				String avatar_large=(String) oobj.get("avatar_large");
				String screenname=(String) oobj.get("screen_name");
				String username = filtername(screenname);
				//(暂时不存)只要是同一个微信开放平台帐号下的公众号，用户的UnionID是唯一的。换句话说，同一用户，对同一个微信开放平台帐号下的不同应用，UnionID是相同的。
				System.out.println(
						" gender : " + sex
						+ " uid : " + uid
						+ " avatar_large : " + avatar_large
						+ " screen_name : " + username
						);
				//判断用户之前是否登陆过，如果登陆过，取出用户信息，设置登录，返回，否则获取用户信息
				 List<PersonalUser>   pus=personalUserServiceInterface.loginweiboUserThird(uid);
				 //如果用户曾经用微博登陆过
		    	 if(pus.size()>0){
				    	//update  用户信息
		    		    if(pus.get(0).getWeibouuid().equals(uid)){
		    		    	pus.get(0).setWeibouuid(uid);     //获取uid
		    		    	pus.get(0).setWeibonickname(username); //获取昵称
		    		    	if(pus.get(0).getWeiboportrait()!=null&&pus.get(0).getWeiboportraitN()!=null){
		    		    		OSSClient client = OSSUnitHelper.getOSSClient(); 
		    		    		OSSUnitHelper.deleteFile(client, ApiController.PORTRAINT_URL, pus.get(0).getWeiboportraitN()); 
		    		    	}
		    		    	String str=saveUserAvatar(avatar_large);
		    		    	String sarr[]=str.split(",");
		    		    	pus.get(0).setWeiboportrait(sarr[0]);
		    		    	pus.get(0).setWeiboportraitN(sarr[1]);
		    		    	request.getSession().setAttribute("sysUser",pus.get(0));
		    		    	personalUserService.insertUser(pus.get(0));
		    		    	//返回首页
		    		    	map.put("home",1);
		    		    }else{
		    		    	 PersonalUser  personalUser=new PersonalUser();
						     personalUser.setWeibouuid(uid);
						     personalUser.setWeibonickname(username); //获取昵称
							 String[] sarr;
							 String str=saveUserAvatar(avatar_large);
							 sarr=str.split(",");
							 personalUser.setWeiboportrait(sarr[0]);
							 personalUser.setWeiboportraitN(sarr[1]);
							 request.getSession().setAttribute("sysUser",personalUser);
						     personalUserService.insertUser(personalUser);  
						     map.put("home",1);
		    		    }
				    }
			}
			return  map;
			
		}
		
		     //手机号验证跳首页之前  第三方wb登录参数的存储
				@RequestMapping("validatewbPhoneProcess")
				public @ResponseBody   Map<String, Object>  validatewbPhoneProcess(String wxcode, String wxstate,
						HttpServletRequest request,String telephone){
					Map<String, Object>  map =new HashMap<>();
					String code = request.getParameter("code");// 客户端传回来的授权码
					String  atokenUrl="https://api.weibo.com/oauth2/access_token";
							String grant_type= "authorization_code";
							String client_id=PropertiesUtils.getPara("wbappkey");
							String client_secret=PropertiesUtils.getPara("wbappsecret");
							String redirect_uri=PropertiesUtils.getPara("wbredirect_uri");
							System.out.println("grant_type:" + grant_type);
							System.out.println("client_id:" + client_id);
							System.out.println("client_secret:" + client_secret);
							System.out.println("redirect_uri:" + redirect_uri);
							System.out.println("code:" + code);
					String ret =HttpGetUtil.httpPost(atokenUrl,grant_type,code,client_id,client_secret,redirect_uri);//返回带token的json字符串
					if(null==ret||"".equals(ret)){
						System.out.println("exception in get token wb");
						map.put("token", 0);
						return map;
					}
					System.out.println(ret);
					com.alibaba.fastjson.JSONObject obj = JSON.parseObject(ret);
					String access_token=(String) obj.get("access_token");//取出token
					String uid=(String) obj.get("uid");//取出uid  第三方平台的id
					
					String apiUrl="https://api.weibo.com/2/users/show.json?"
							+ "access_token="+access_token
							+ "&uid="+uid;
					
					String uinfoma = HttpGetUtil.httpGet(apiUrl);// 返回用户信息的字符串
					System.out.println(uinfoma);
					
					//判断用户之前是否登陆过，如果登陆过，取出用户信息，设置登录，返回，否则获取用户信息
					
					 if (uinfoma != null) {
							com.alibaba.fastjson.JSONObject oobj = JSON.parseObject(uinfoma);
							
							String sex=("m".equals((String)oobj.get("gender")))?"男":"女";
							String avatar_large=(String) oobj.get("avatar_large");
							String screenname=(String) oobj.get("screen_name");
							String username = filtername(screenname);
							//(暂时不存)只要是同一个微信开放平台帐号下的公众号，用户的UnionID是唯一的。换句话说，同一用户，对同一个微信开放平台帐号下的不同应用，UnionID是相同的。
							System.out.println(
									" gender : " + sex
									+ " uid : " + uid
									+ " avatar_large : " + avatar_large
									+ " screen_name : " + username
									);
							List<PersonalUser>	users= personalUserService.findUsername(telephone);
							//如果有说明注册过
							 if(users.size()>0){
								 //注册过手机号但是没有第三方登录过微信
								 if(users.get(0).getWeibouuid()==null){
											//之前未登录过
									 users.get(0).setWeibouuid(uid);     //获取openid
									 users.get(0).setWeibonickname(username); //获取昵称
									 users.get(0).setCreateTime(new Date());
									 String str=saveUserAvatar(avatar_large);
									 String sarr[]=str.split(",");
									 users.get(0).setWeiboportrait(sarr[0]);
									 users.get(0).setWeiboportraitN(sarr[1]);
									 request.getSession().setAttribute("sysUser", users.get(0));
								     personalUserService.insertUser(users.get(0));
										    //返回首页
								     map.put("home",1);
									//注册过手机号，也同时用过微信登录过
								 }else{
									 //曾 经注册而且用同一个微信手机号绑定
									 if(users.get(0).getWeibouuid().equals(uid)){
										 
										 users.get(0).setWeibonickname(username); //获取昵称
										 users.get(0).setCreateTime(new Date());
										 if(users.get(0).getWeiboportrait()!=null&&users.get(0).getWeiboportraitN()!=null){
											 OSSClient client = OSSUnitHelper.getOSSClient(); 
											 OSSUnitHelper.deleteFile(client, ApiController.PORTRAINT_URL, users.get(0).getWeiboportraitN()); 
										 }
										 String str=saveUserAvatar(avatar_large);
										 String sarr[]=str.split(",");
										 users.get(0).setWeiboportrait(sarr[0]);
										 users.get(0).setWeiboportraitN(sarr[1]);
										 request.getSession().setAttribute("sysUser", users.get(0));
										 personalUserService.insertUser(users.get(0));
										 map.put("home",1);
										// 如果同一个手机号登录不同的微信号
									 }else{
										 //绑定新的微信号登录
										 users.get(0).setWeibouuid(uid);
										 users.get(0).setWeibonickname(username); //获取昵称
										 users.get(0).setCreateTime(new Date());
										 if(users.get(0).getWeiboportrait()!=null&&users.get(0).getWeiboportraitN()!=null){
											 OSSClient client = OSSUnitHelper.getOSSClient(); 
											 OSSUnitHelper.deleteFile(client, ApiController.PORTRAINT_URL, users.get(0).getWeiboportraitN()); 
										 }
										 String str=saveUserAvatar(avatar_large);
										 String sarr[]=str.split(",");
										 users.get(0).setWeiboportrait(sarr[0]);
										 users.get(0).setWeiboportraitN(sarr[1]);
										 request.getSession().setAttribute("sysUser", users.get(0));
										 personalUserService.insertUser(users.get(0));
										 map.put("home",1);
										 
									 }
								 }
							//如果没有注册过手机号	 
							  }else{
								  List<PersonalUser>	puser=  personalUserService.loginweiboUserThird(uid);
								  if(puser.size()>0){
									  //有openid  更新手机号
									     puser.get(0).setUsername(telephone);
									     puser.get(0).setWeibonickname(username); //获取昵称
									     puser.get(0).setCreateTime(new Date());
									     if(puser.get(0).getWeiboportrait()!=null&&puser.get(0).getWeiboportraitN()!=null){
									    	 OSSClient client = OSSUnitHelper.getOSSClient(); 
									    	 OSSUnitHelper.deleteFile(client, ApiController.PORTRAINT_URL, puser.get(0).getWeiboportraitN()); 
									     }
										 String str=saveUserAvatar(avatar_large);
										 String sarr[]=str.split(",");
										 puser.get(0).setWeiboportrait(sarr[0]);
										 puser.get(0).setWeiboportraitN(sarr[1]);
										 request.getSession().setAttribute("sysUser", puser.get(0));
									     personalUserService.insertUser(puser.get(0));  
									     map.put("home",1);
								  }else{
									  //没有openid和手机号    insert 手机号和三方登录等信息
									     PersonalUser  personalUser=new PersonalUser();
									     personalUser.setUsername(telephone);
									     personalUser.setWeibouuid(uid);
									     personalUser.setWeibonickname(username); //获取昵称
									     personalUser.setCreateTime(new Date());
										 String[] sarr;
										 String str=saveUserAvatar(avatar_large);
										 sarr=str.split(",");
										 personalUser.setWeiboportrait(sarr[0]);
										 personalUser.setWeiboportraitN(sarr[1]);
										 request.getSession().setAttribute("sysUser", personalUser);
									     personalUserService.insertUser(personalUser);  
									     map.put("home",1);
									  
								  }
							  }
					 
					 }else{
						 //返回用户信息出错
						 map.put("Nouinfoma", -1);
					 }
					 
				
					return map;
			
				}
		

		/**解析accesstoken
		 * @param ret
		 * @param string
		 * @return
		 */
		private String getAccessToken(String ret, String string) {
			String[] arraystr1 = ret.split("&");
			String result = "";
			if(null!=arraystr1&&arraystr1.length>0){
				for(String tmpstr:arraystr1){
					String[] arraystr2 = tmpstr.split("=");
					if(null!=arraystr2&&arraystr2.length==2){
						if(arraystr2[0].equals(string)){
							result = arraystr2[1];
							break;
						}
					}
				}
			}
			
			return result;
		}
		/**解析openid
		 * @param inpuStr
		 * @return
		 */
		private String getOpenId(String inpuStr){
			String result = "";
			int startindex = inpuStr.indexOf("{");
			int endindex = inpuStr.indexOf("}") + 1;
		      if(startindex>=0&&endindex>0&&endindex>startindex){
		    	  result = inpuStr.substring(startindex, endindex);
		      }
		    	  
		      return result;
		}
		
		
		
		/**过滤昵称中的特殊字符
		 * @param niceName
		 * @return
		 */
		private String filtername(String niceName) {
			String result = "";
			
			for (int i=0;i<niceName.length();i++){
				int c=niceName.codePointAt(i);
				if (c<0x0000||c>0xffff) {
				    //return false;
					 
				} else {
					result += niceName.substring(i, i+1);
				}
			}

			return result;
		}
		/**保存用户头像
		 * @param figureurl_qq_2
		 * @return
		 */
		private String saveUserAvatar(String figureurl_qq_2) {
			String filename = "";
			try {
				// 得到上传文件的内容
	            byte[] useravatar  = HttpGetUtil.downloadPortrait(figureurl_qq_2);
	            InputStream sbs = byte2Input(useravatar); 
				//判断是否有图片
				if(useravatar.length>0){
					
					OSSClient client = OSSUnitHelper.getOSSClient(); 
					// 通过生成的随机数拼接上文件的后缀名，生成新的文件名
					String newFilename = (new SimpleDateFormat("yyyyMMddhhmmss")).format(new Date())
									   + ((int)(Math.random()*1000) + 1000)
									   + ".jpg";
					OSSUnitHelper.uploadFile2OSS(client, sbs, newFilename, ApiController.USERHEADW_URL);
					String url=OSSUnitHelper.getUrl(client, ApiController.USERHEADW_URL, newFilename);
					filename=url+","+newFilename;
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			//上传成功，写返回文件名称和存储路径
			return filename;
		
		}
		
		
		//byte[]转inputstream
		/**
		 * 
		 * @param buf
		 * @return
		 */
		public static final InputStream byte2Input(byte[] buf) {  
	        return new ByteArrayInputStream(buf);  
	    }  
		
		
		@RequestMapping("uptest")
		public  PersonalUser  uptest(String username){
			List<PersonalUser>  personalUser=personalUserService.findUsername(username);
			personalUser.get(0).setCreateTime(new Date());
			personalUser.get(0).setWechatnickname("小太阳");
			personalUser.get(0).setWechatportraitN("ssssssssssssssssssssssss");
			personalUser.get(0).setUsername(username);
			return personalUserService.insertUser(personalUser.get(0));
		}


}
